import {celebrate, Joi} from "celebrate";
import {Router, Request} from "express";
import {alipayCashier} from "../alipay/payment";
import {RechargeModel} from "../database/models/recharge";
import {RechargeOrderModel} from "../database/models/rechargeOrder";
import {wechatPayCashier} from "../wechat/wechatCashier";
import {InternalError} from "./error";
import {withRecharge, Response, withUser} from "./middlewareType";
import {jwtAuthMiddleware} from "./passort";
import ms = require("ms");

const router = Router()

router.post('/:rechargeId',
  jwtAuthMiddleware,
  celebrate({
      params: Joi.object().keys({rechargeId: Joi.string().required()}),
      body: Joi.object().keys({
        payType: Joi.string().required().valid(['wechatPay', 'aliPay'])
      })
    }
  ),
  async (req: Request & withRecharge, res: Response, next) => {
    const r = await RechargeModel.findOne({_id: req.params.rechargeId, state: "on"}).lean()

    if (r) {
      req.recharge = r
      next()
    } else {
      res.error(InternalError('NO_SUCH_PRODUCT'))
    }
  },
  async (req: Request & withRecharge & withUser, res: Response) => {
    const recharge = req.recharge

    const inviteBy = req.user.inviteBy || null

    const ro = new RechargeOrderModel({
      recharge,
      player: req.user.id,
      coin: recharge.coin,
      freeCoin: recharge.freeCoin,
      gem: recharge.gem,
      state: 'unpaid',
      createAt: new Date(),
      RMBCost: recharge.RMBCost,
      inviteBy
    })
    await ro.save()

    const paymentArg = {
      title: recharge.name,
      detail: recharge.name,
      price: recharge.RMBCost,
      order: ro.id,
      type: 'RechargeOrder',
      fromIP: req.ip
    }

    const cashier = req.body.payType === 'wechatPay' ? wechatPayCashier : alipayCashier

    const payOrder = await cashier.createPaymentOrder(paymentArg, ms('15min'))

    res.json({
      ok: true,
      data: {
        rechargeOrder: ro,
        payOrder: payOrder.prepay
      }
    })
  }
)

export default router
